package com.softeem.score.manager.service.impl;


import com.softeem.score.manager.properties.SmsProperties;
import com.softeem.score.manager.service.SmsService;
import com.softeem.score.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendCode(String phone) {
        String code = RandomStringUtils.randomNumeric(6);
        //2 把生成验证码放到redis里面，设置过期时间
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        //3 向手机号发送短信验证码
        sendMessage(phone, code);
    }

    //发送短信验证码的方法
    private void sendMessage(String phone, String code) {
        String host = SmsProperties.HOST;
        String path = SmsProperties.PATH;
        String method = SmsProperties.METHOD;
        String appcode = SmsProperties.APPCODE;
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:" + code + ",**minute**:5");
        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。
        // 参考文档：http://help.guoyangyun.com/Problem/Qm.html
        querys.put("smsSignId", SmsProperties.SMSSIGNID);
        //querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        querys.put("templateId", SmsProperties.TEMPLATEID);
        Map<String, String> bodys = new HashMap<>();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
